import pandas as pd

from calc_core.utils import _three_sigma


def gradient_strategy(frame_data_base, frame_data_user, frame_base_start_index, frame_user_start_index, frame_num):
    if len(frame_data_base) < frame_base_start_index + frame_num:
        raise Exception(print("frame_data_base帧数越界！"))
    if len(frame_data_user) < frame_user_start_index + frame_num:
        raise Exception(print("frame_data_user帧数越界！"))

    gradients_all = []
    for i in range(0, frame_num):
        frame_base_key_points = frame_data_base[frame_base_start_index + i][0].key_points
        frame_user_key_points = frame_data_user[frame_user_start_index + i][0].key_points
        if len(frame_base_key_points) != len(frame_user_key_points):
            raise Exception(print("关键点个数不匹配！"))
        gradients = []
        for j in range(0, len(frame_base_key_points)):  # 对每个关键点计算梯度
            base_key_point = frame_base_key_points[j]
            user_key_point = frame_user_key_points[j]
            gradient = _get_gradient(base_key_point, user_key_point)
            gradients.append(gradient)
        gradients_all.append(gradients)
    # gradients_all是一个x行（x为参与计算的标志点个数）y列（列为frame frame_num）
    gradients_all_df = pd.DataFrame(gradients_all)
    for columnName, value in gradients_all_df.iteritems():
        gradients_all_df[columnName] = _three_sigma(value) # 将异常点消除
    return sum(gradients_all_df.std(axis=0))


def _get_gradient(coordinate_base, coordinate_user):  # y1- y0 / x1 - x0
    coordinate_base_x, coordinate_base_y, _ = coordinate_base
    coordinate_user_x, coordinate_user_y, _ = coordinate_user
    if (coordinate_user_x - coordinate_base_x) == 0:
        return 0
    gradient = (coordinate_user_y - coordinate_base_y) / (coordinate_user_x - coordinate_base_x)
    return gradient
